package com.hysf.web.controllers;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.hysf.configs.OssConfig;
import com.hysf.web.model.ProductUploadRequest;
import com.hysf.web.model.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping ("/products")
public class ProductsController {
	@Autowired
	private OSS ossClient;
	
	@Autowired
	private OssConfig ossConfig;
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ResponseResult upload(@RequestParam("goodsImg") MultipartFile[] productImages,
	                             @ModelAttribute ProductUploadRequest productUploadRequest) {
		if (productImages.length == 0) {
			return ResponseResult.builder().code(400).msg("请上传商品图片").build();
		}
		StringBuilder sb = new StringBuilder();
		for (MultipartFile productImage : productImages) {
			if (productImage.isEmpty()) {
				continue;
			}
			String originalFilename = productImage.getOriginalFilename(); // 文件名
			String fileExtension = ""; // 文件扩展名
			if (originalFilename.contains(".")) {
				fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); // 扩展名
			}
			System.out.println("原文件名：" + originalFilename);
			String objectKey = "products/" + UUID.randomUUID() + fileExtension;
			
			PutObjectRequest putObjectRequest;
			try {
				// 上传文件 到 oss
				putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(),objectKey,productImage.getInputStream());
				ossClient.putObject(putObjectRequest);
				
				String fileUrl = ossConfig.getUrlPrefix() + File.separator + objectKey;
				sb.append(fileUrl).append(", ");
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		System.out.println("上传文件到Oss的url为：" + sb);
		System.out.println("productUploadRequest = " + productUploadRequest);
		return ResponseResult.builder().code(1).msg("上传成功").build();
	}
}
